<template>
  <div class="main">
    <PcHeader
      :titleNameImg="titleImg"
      :titleBgImg="titleBgImg"
      :isEmbed="getParam('win') !== '1'"
      :popupUrl="popupUrl"
      :buttonOrder="['Disclaimer', 'ClientIcon']"
    >
      <template slot="buttons-left">
        <Guide
          :visible="showGuideIndex === 1"
          content="如果您在使用功能中有疑惑和难点，可点击此处查看详细介绍视频"
          buttonContent="下一步"
          @hiddenGuide="showGuideIndex = 2"
        >
          <div slot="reference" class="introduce" @click.stop="jumpVideo">
            <span>功能介绍</span>
          </div>
        </Guide>
        <Guide
          :visible="showGuideIndex === 2"
          content="如果您在使用功能中有任何建议或意见，我们非常欢迎您的反馈，您的每一条建议都是我们不断进步和完善的动力"
          buttonContent="我知道了"
          @hiddenGuide="hiddenGuide"
        >
          <div slot="reference" class="introduce" @click.stop="jumpFeedBack">
            <span>意见反馈</span>
          </div>
        </Guide>
      </template>
    </PcHeader>
    <div class="block">
      <CusFilter
        :showType="showType"
        :tabValue="tabValue"
        :radioValue="radioValue"
        :isShowTurnover="isShowTurnover"
        @update:tabValue="updateTabValue"
        @update:radioValue="updateRadioValue"
        @update:isShowTurnover="updateShowTurnover"
      />
      <keep-alive>
        <div class="table-container" v-clickOutside="initActiveBlock" v-if="showType === 'home'">
          <Table
            v-for="(columns, index) in columnsArr"
            :key="index"
            :hasGuide="index === 0"
            :activeBlock="activeBlock"
            :activeInfo="activeInfoArr[index]"
            :isShowTurnover="isShowTurnover"
            :title="`${titleArr[index]}期趋势`"
            :columns="columns"
            :loading="homeLoading"
            :tableData="tableDataArr[index]"
            :titleTipsContent="config.tipsArr[index].titleTips"
            @lookmore="setShowType('history', index)"
            @updateActiveBlock="updateActiveBlock"
          />
        </div>
      </keep-alive>
      <History
        v-if="showType === 'history'"
        :historyIndex="historyIndex"
        :title="`${titleArr[historyIndex]}期趋势历史`"
        :blockType="tabValue"
        @goback="setShowType('home')"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { CusFilter, Table, History } from '_c/Home/index.ts';
import { reqDetail } from '_a';
import { errorReport, getParam } from '_t';
import {
  useHomeData,
  useActiveBlock,
  useFilter,
  useTimingUpdate,
  useHeader
} from '@/hooks/index.ts';
import { BlockType } from '@/types/api';
import { HistoryIndex } from '@/types/history';
import { radioNum } from '@/types/filter';
import config from '@/config/index.ts';
const {
  imgs: { titleImg, titleBgImg },
  storageKey: { firstEntry }
} = config;

const instance = getCurrentInstance() as any;
// 获取当前缓存实例
const localforageIns = instance.proxy.$localforageIns;
const { popupUrl, jumpVideo, jumpFeedBack, getPopupUrl, showGuideIndex, hiddenGuide } =
  useHeader(localforageIns);
/**
 * 设置选中板块逻辑
 * activeBlock - 当前选中的板块code
 * rankArr - 当前三个表格的排名
 * initActiveBlock - 初始化选中板块
 * setActiveBlock - 设置选中板块
 */
const { activeBlock, activeBlockMarket, activeInfoArr, initActiveBlock, setActiveBlock } =
  useActiveBlock();
const updateActiveBlock = ({ code, market }: { code: string; market: string }) => {
  setActiveBlock({ code, market });
  // 点击的时候需要更新一下表格数据，防止调用的排名和表格显示的不同
  getHomeData();
  getDetail();
};
const getDetail = () => {
  reqDetail({ code: activeBlock.value, market: activeBlockMarket.value, date: date.value })
    .then(
      ({
        rise_range_rank,
        rise_range_rank_change,
        g_percent_rank,
        g_percent_rank_change,
        n_percent_rank,
        n_percent_rank_change
      }) => {
        activeInfoArr.value = [
          { rank: rise_range_rank, rankChange: rise_range_rank_change },
          { rank: g_percent_rank, rankChange: g_percent_rank_change },
          { rank: n_percent_rank, rankChange: n_percent_rank_change }
        ];
      }
    )
    .catch(error => {
      errorReport({
        name: `首页获取数据详情失败。${error.name}`,
        message: error.message,
        stack: error.stack
      });
    });
};
/**
 * 过滤逻辑
 * tabValue - 全部，行业，概念
 * radioValue - 上榜标红展示
 * isShowTurnover - 是否显示成交额
 * setTabValue - 设置过滤
 * setRadioValue - 设置是否显示成交额
 * setShowTurnover - 设置是否显示成交额
 */
const { tabValue, radioValue, isShowTurnover, setTabValue, setRadioValue, setShowTurnover } =
  useFilter();

const updateTabValue = (value: BlockType) => {
  const statOptions = {
    '': 'all',
    cn_industry: 'industry',
    cn_concept: 'concept'
  };
  window.TA.log({ id: `${config.statHomePage}.stockclass_${statOptions[value]}.click` });
  setTabValue(value);
  getHomeData();
};
const updateRadioValue = (value: string) => {
  const statOptions: Record<string, string> = {
    [`${radioNum.short},${radioNum.medium},${radioNum.long}`]: 'shortmediumlong',
    [`${radioNum.short},${radioNum.medium}`]: 'shortmedium',
    [`${radioNum.short},${radioNum.long}`]: 'shortlong'
  };
  window.TA.log({ id: `${config.statHomePage}.rankclass_${statOptions[value]}.click` });
  setRadioValue(value);
  getHomeData().then(() => {
    setRadioRank(tableDataArr.value, true);
  });
};
const updateShowTurnover = (value: boolean) => {
  setShowTurnover(value);
  getHomeData();
};

/**
 * 获取数据逻辑
 * date - 接口返回日期
 * tableDataArr - 表格数据
 * columnsArr - 表头列
 * titleArr - 表格标题
 * setRadioRank - 设置上榜排名
 * getHomeData - 获取数据
 */
const { date, tableDataArr, columnsArr, titleArr, setRadioRank, getHomeData, homeLoading } =
  useHomeData(radioValue, tabValue);

const showType = ref<'home' | 'history'>('home');
const historyIndex = ref<HistoryIndex>(0);
const setShowType = (cusShowType: 'home' | 'history', index?: HistoryIndex) => {
  showType.value = cusShowType;
  if (index !== void 0) {
    historyIndex.value = index;
  }
};

// 定时更新数据
useTimingUpdate(() => {
  if (showType.value !== 'home') {
    return;
  }
  // 获取数据之后更新排名数据
  getHomeData();
  activeBlock.value && getDetail();
});

onMounted(() => {
  localforageIns.getItem(firstEntry).then((res: boolean) => {
    if (!res) {
      showGuideIndex.value = 1;
    }
  });
  popupUrl.value = getPopupUrl();
  getHomeData();
  window.TA.log({ id: `${config.statHomePage}` });
});
</script>

<style scoped lang="less">
.main {
  margin: 6px 8px;
  display: flex;
  flex-direction: column;
  .introduce {
    position: relative;
    height: 22px;
    margin: 0 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    z-index: 10;
    &::after {
      content: '';
      position: absolute;
      width: 1px;
      height: 8px;
      background: rgba(255, 255, 255, 0.25);
      right: -13px;
      top: 8px;
    }
    span {
      font-family: MicrosoftYaHei;
      font-size: 14px;
      color: #8c8c8c;
      letter-spacing: 0;
      text-align: right;
      line-height: 16px;
      font-weight: 400;
      &:hover {
        color: #40a9ff;
      }
    }
  }
  .block {
    display: flex;
    flex-direction: column;
    min-width: 1166px;
    background: #161616;
    border-radius: 4px;
    padding: 8px;
    .table-container {
      margin-top: 6px;
      display: flex;
      justify-content: space-between;
      height: calc(100vh - 100px);
    }
  }
}
</style>
